package com.mes.handler.plan;

import com.basis.utils.HibernateDao;
import com.mes.data.EmesColor;
import com.mes.data.EmesProcess;
import com.mes.data.EmesShape;
import com.mes.manufacture.data.EmesoJobOrder;
import com.mes.manufacture.data.EmesoJobOrderExe;
import com.mes.manufacture.data.EmesoJobOrderMaterial;
import com.mes.manufacture.data.EmesoManuOrder;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.plm.Product;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 生产工单下达
 */
public class ManuOrderAuditHandler extends BaseActionHandler {
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();
		String msg = "";
		try {
			//设置Admin权限
			OBContext.setAdminMode();
			jsonRep.put("flag", true);
			jsonRep.put("message", "处理成功");
			String jsonIds = new JSONObject(content).getString("ids");
			// 获取勾选的呼叫投料
			String[] ids = jsonIds.split(",");
			for (String id : ids) {
				EmesoManuOrder emo = OBDal.getInstance().get(EmesoManuOrder.class, id);
				if (emo.getStatus().equalsIgnoreCase("CREATE")) {
					emo.setStatus("ISSUED");
					OBDal.getInstance().save(emo);
				} else if (emo.getStatus().equalsIgnoreCase("ISSUED")) {
					msg += "【订单编码为：" + emo.getCode() + "的订单已经下发，请仔细检查】";
				} else {
					msg += "【订单编码为：" + emo.getCode() + "的订单无法下发，因为该订单不是创建状态】";
				}
			}

			if ("".equals(msg)) {
				for (String id : ids) {
					EmesoManuOrder emo = OBDal.getInstance().get(EmesoManuOrder.class, id);
					//生成作业订单
					createJobOrder(emo);
				}

				jsonRep.put("flag", true);
				jsonRep.put("message", "处理成功");
				OBDal.getInstance().commitAndClose();
				return jsonRep;
			} else {
				jsonRep.put("flag", false);
				jsonRep.put("message", msg);
				OBDal.getInstance().rollbackAndClose();
				return jsonRep;
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			try {
				jsonRep.put("flag", false);
				jsonRep.put("message", e.getMessage());
				return jsonRep;
			} catch (Exception e2) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return null;
	}

	//同步生成
	private void createJobOrder(EmesoManuOrder emo) {
		int qty = emo.getQty().intValue();

		EmesoJobOrder jobOrder = null;
		for (int i = 0;i < qty;i ++) {
			jobOrder = new EmesoJobOrder();
			jobOrder.setProduct(emo.getProduct());
			jobOrder.setCode(emo.getCode() + "-" + (i + 1));
			jobOrder.setQty(1l);
			jobOrder.setEmesoManuorder(emo);
			jobOrder.setStatus("CREATE");
			jobOrder.setDescription(emo.getDescription());

			//根据小时级计划，计算预计开工时间


			OBDal.getInstance().save(jobOrder);

			createJobOrderExe(emo, jobOrder);

			addMaterial(jobOrder, emo);
		}
	}

	private void createJobOrderExe(EmesoManuOrder emo, EmesoJobOrder jobOrder) {
		String sql = "select Emes_Process_id from Emes_Process where isactive = 'Y' and Emes_Process_Route_Id = ?";
		String routeId = null;
		//如果
		if (emo.getEmesProcessRoute() == null) {
			String hql = "select emes_process_route_id from emes_process_route where m_product_id = ? limit 1";
			Map<String, Object> routeMap = HibernateDao.queryUnique(hql, emo.getProduct().getId());
			if (routeMap == null) {
				throw new RuntimeException("当前形体未设置工艺路线！");
			}
			routeId = (String)routeMap.get("emes_process_route_id");
		} else {
			routeId = emo.getEmesProcessRoute().getId();
		}

		List<Map<String, Object>> processList = HibernateDao.query(sql, routeId);
		if (processList == null || processList.isEmpty()) {
			throw new RuntimeException("当前形体[" + emo.getProduct().getSearchKey() + " - " + emo.getProduct().getName() + "]未配置有效工艺路线！");
		}

		EmesProcess process = null;
		EmesoJobOrderExe jobExe = null;
		for (Map<String, Object> map : processList) {
			process = (EmesProcess) OBDal.getInstance().get(EmesProcess.ENTITY_NAME, map.get("EMES_PROCESS_ID"));

			jobExe = new EmesoJobOrderExe();
			jobExe.setEmesProcess(process);
			jobExe.setRouteName(process.getName());
			jobExe.setRouteNo(process.getRouteNo());
			jobExe.setEmesoJobOrder(jobOrder);

			//计算开工、完工时间
			//jobExe.setPlanedDateFrom();
			//jobExe.setPlanedDateTo();

			OBDal.getInstance().save(jobExe);
		}
	}

	/**
	 * 添加作业工单辅料列表
	 * @param jobOrder
	 */
	private void addMaterial(EmesoJobOrder jobOrder, EmesoManuOrder order) {
		String sql = "select jpb.m_product_id, jp.emes_size_id, jpb.emes_color_id, jpb.emes_shape_id,   " +
				"       (select pis.qty from emes_pbom p, emes_pbom_item pi   " +
				"         where p.emes_pbom_id = pi.emes_pbom_id  " +
				"           and pi.emes_pbom_item_id = pis.emes_pbom_item_id  " +
				"           and pis.emes_color_id = jpb.emes_color_id  " +
				"           and pis.emes_size_id = jp.emes_size_id  " +
				"           and pis.m_product_id = jpb.m_product_id  " +
				"           and mo.m_product_id = p.m_product_id) qty  " +
				"  from emeso_job_plan_bom jpb, emeso_job_plan jp, emeso_manuorder mo  " +
				" where jpb.emeso_job_plan_id = jp.emeso_job_plan_id   " +
				"   and jpb.emes_shape_id is not null  " +
				"   and jp.emeso_manuorder_id = mo.emeso_manuorder_id  " +
				"   and mo.emeso_manuorder_id = '" + order.getId() + "'";
		List<Map<String, Object>> result = HibernateDao.query(sql);
		EmesoJobOrderMaterial jobMaterial = null;

		for (Map<String, Object> map : result) {
			jobMaterial = new EmesoJobOrderMaterial();

			jobMaterial.setEmesColor(OBDal.getInstance().get(EmesColor.class, map.get("EMES_COLOR_ID")));
			jobMaterial.setEmesoJobOrder(jobOrder);
			jobMaterial.setEmesShape(OBDal.getInstance().get(EmesShape.class, map.get("EMES_SHAPE_ID")));
			jobMaterial.setProduct(OBDal.getInstance().get(Product.class, map.get("M_PRODUCT_ID")));
			jobMaterial.setQty((BigDecimal)map.get("QTY"));
			jobMaterial.setStatus("CREATE");

			OBDal.getInstance().save(jobMaterial);
		}
	}
}
